﻿using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using QFramework;

namespace HKTools
{
    /// <summary>
    /// 简易题库模块的总控脚本
    /// </summary>
    public class HK_UI_SimpleQuizPanel : HKSimpleQuiz_BaseController
    {
        [Header("题型切换")]
        [SerializeField] Toggle single_Toggle;
        [SerializeField] Toggle multiple_Toggle;
        [SerializeField] Toggle trueFalse_Toggle;
        [SerializeField] Toggle blank_Toggle;
        [SerializeField] Toggle shortAnswer_Toggle;

        [Header("题目预设体")]
        [SerializeField] HK_SingleChoiceItem singleItem_Prefab;
        [SerializeField] HK_MultipleChoiceItem multipleItem_Prefab;
        [SerializeField] HK_TrueFalseItem trueFalseItem_Prefab;
        [SerializeField] HK_BlankItem blankItem_Prefab;
        [SerializeField] HK_ShortAnswerItem shortAnswerItem_Prefab;

        [Header("题目的父物体")]
        [SerializeField] GameObject singleChoicePanel;
        [SerializeField] RectTransform singleChoiceContent;
        [SerializeField] GameObject multipleChoicePanel;
        [SerializeField] RectTransform multipleChoiceContent;
        [SerializeField] GameObject trueFalsePanel;
        [SerializeField] RectTransform trueFalseContent;
        [SerializeField] GameObject blankPanel;
        [SerializeField] RectTransform blankContent;
        [SerializeField] GameObject shortAnswerPanel;
        [SerializeField] RectTransform shortAnswerContent;

        [Header("UI组件")]
        [SerializeField] Button submit_Btn;
        [SerializeField] GameObject tipsPanel_Go;
        [SerializeField] Text tips_Text;
        [SerializeField] Button left_Btn;
        [SerializeField] Button right_Btn;
        [SerializeField] HK_UI_QuizTipsPanel quizTipsPanel;

        [Header("布局配置")]
        [SerializeField] Vector2 normalSingleSize = new Vector2(1000, 430);
        [SerializeField] Vector2 normalMultipleSize = new Vector2(1000, 430);
        [SerializeField] Vector2 normalTrueFalseSize = new Vector2(1000, 200);
        [SerializeField] Vector2 normalBlankSize = new Vector2(1000, 200);
        [SerializeField] Vector2 normalShortAnswerSize = new Vector2(1000, 350);
        [SerializeField] Vector2 wrongSingleSize = new Vector2(1000, 620);
        [SerializeField] Vector2 wrongMultipleSize = new Vector2(1000, 620);
        [SerializeField] Vector2 wrongTrueFalseSize = new Vector2(1000, 280);
        [SerializeField] Vector2 wrongBlankSize = new Vector2(1000, 280);
        [SerializeField] Vector2 wrongShortAnswerSize = new Vector2(1000, 430);

        // 题目列表
        List<HK_SingleChoiceItem> allSingle_List = new List<HK_SingleChoiceItem>();
        List<HK_MultipleChoiceItem> allMultiple_List = new List<HK_MultipleChoiceItem>();
        List<HK_TrueFalseItem> allTrueFalse_List = new List<HK_TrueFalseItem>();
        List<HK_BlankItem> allBlank_List = new List<HK_BlankItem>();
        List<HK_ShortAnswerItem> allShortAnswer_List = new List<HK_ShortAnswerItem>();

        // 面板列表和网格布局组件
        List<GameObject> quesPanel_List = new List<GameObject>();
        Dictionary<GameObject, GridLayoutGroup> panelToGridMap = new Dictionary<GameObject, GridLayoutGroup>();

        // 数据和状态
        IHK_SimpleQuizModel quesDataModel;
        bool isAllQuesComplete;
        int singleDone_Num = 0;
        int multipleDone_Num = 0;
        int trueFalseDone_Num = 0;
        int blankDone_Num = 0;
        int shortAnswer_Num = 0;

        // 记录上次检查状态，刷新答题进度
        float judgeInterval = 0.25f; // 检查间隔(秒)
        float lastJudgeTime = 0;

        void Awake()
        {
            RegisterEvents();
            InitializeComponents();
        }

        void Update()
        {
            // 按时间间隔检查答题进度
            if (Time.time - lastJudgeTime > judgeInterval)
            {
                JudgeSubjectDoneProgress();
                lastJudgeTime = Time.time;
            }
        }

        /// <summary>
        /// 初始化组件引用
        /// </summary>
        void InitializeComponents()
        {
            quesDataModel = this.GetModel<IHK_SimpleQuizModel>();
            submit_Btn.onClick.AddListener(OnClickSubmitBtn);

            // 添加面板到列表
            quesPanel_List.Add(singleChoicePanel);
            quesPanel_List.Add(multipleChoicePanel);
            quesPanel_List.Add(trueFalsePanel);
            quesPanel_List.Add(blankPanel);
            quesPanel_List.Add(shortAnswerPanel);

            // 建立面板和网格布局的映射
            panelToGridMap[singleChoicePanel] = singleChoiceContent.GetComponent<GridLayoutGroup>();
            panelToGridMap[multipleChoicePanel] = multipleChoiceContent.GetComponent<GridLayoutGroup>();
            panelToGridMap[trueFalsePanel] = trueFalseContent.GetComponent<GridLayoutGroup>();
            panelToGridMap[blankPanel] = blankContent.GetComponent<GridLayoutGroup>();
            panelToGridMap[shortAnswerPanel] = shortAnswerContent.GetComponent<GridLayoutGroup>();

            // 注册Toggle事件
            single_Toggle.onValueChanged.AddListener(OnSingleToggleChanged);
            multiple_Toggle.onValueChanged.AddListener(onMultipleToggleChanged);
            trueFalse_Toggle.onValueChanged.AddListener(OnTrueFalseToggleChanged);
            blank_Toggle.onValueChanged.AddListener(OnBlankToggleChanged);
            shortAnswer_Toggle.onValueChanged.AddListener(OnShortAnswerToggleChanged);
        }

        /// <summary>
        /// 注册事件监听
        /// </summary>
        void RegisterEvents()
        {
            this.RegisterEvent<Event_InitQuesItems>(args => OnInitQuesItems())
                .UnRegisterWhenGameObjectDestroyed(gameObject);

            this.RegisterEvent<Event_ShowWrongQuesItem>(args => OnShowWrongQuesItem())
                .UnRegisterWhenGameObjectDestroyed(gameObject);

            this.RegisterEvent<Event_QuizComplete>(args => HKDebug.Log("答题完成!"))
                .UnRegisterWhenGameObjectDestroyed(gameObject);

            this.RegisterEvent<Event_QuizGiveUp>(args => HKDebug.Log("放弃答题！"))
                .UnRegisterWhenGameObjectDestroyed(gameObject);
        }

        /// <summary>
        /// 初始化题库面板
        /// </summary>
        void OnInitQuesItems()
        {
            if (quesDataModel == null || quesDataModel.QuizData.Value == null)
            {
                HKDebug.LogError("题库数据为空！");
                return;
            }

            if (quesDataModel.Single_Num.Value == 0)
            {
                singleChoicePanel.SetActive(false);
                single_Toggle.gameObject.SetActive(false);
            }

            if (quesDataModel.Multiple_Num.Value == 0)
            {
                multipleChoicePanel.SetActive(false);
                multiple_Toggle.gameObject.SetActive(false);
            }

            if (quesDataModel.TrueFalse_Num.Value == 0)
            {
                trueFalsePanel.SetActive(false);
                trueFalse_Toggle.gameObject.SetActive(false);
            }

            if (quesDataModel.Blank_Num.Value == 0)
            {
                blankPanel.SetActive(false);
                blank_Toggle.gameObject.SetActive(false);
            }

            if (quesDataModel.ShortAnswer_Num.Value == 0)
            {
                shortAnswerPanel.SetActive(false);
                shortAnswer_Toggle.gameObject.SetActive(false);
            }

            submit_Btn.gameObject.SetActive(true);

            // 设置网格大小
            panelToGridMap[singleChoicePanel].cellSize = normalSingleSize;
            panelToGridMap[multipleChoicePanel].cellSize = normalMultipleSize;
            panelToGridMap[trueFalsePanel].cellSize = normalTrueFalseSize;
            panelToGridMap[blankPanel].cellSize = normalBlankSize;
            panelToGridMap[shortAnswerPanel].cellSize = normalShortAnswerSize;

            // 更新Toggle文本
            single_Toggle.GetComponentInChildren<Text>().text = "单选题(0/" + quesDataModel.Single_Num.Value.ToString() + ")";
            multiple_Toggle.GetComponentInChildren<Text>().text = "多选题(0/" + quesDataModel.Multiple_Num.Value.ToString() + ")";
            trueFalse_Toggle.GetComponentInChildren<Text>().text = "判断题(0/" + quesDataModel.TrueFalse_Num.Value.ToString() + ")";
            blank_Toggle.GetComponentInChildren<Text>().text = "填空题(0/" + quesDataModel.Blank_Num.Value.ToString() + ")";
            shortAnswer_Toggle.GetComponentInChildren<Text>().text = "简答题(0/" + quesDataModel.ShortAnswer_Num.Value.ToString() + ")";

            // 清理所有题目
            for (int i = 0; i < allSingle_List.Count; i++)
                Destroy(allSingle_List[i].gameObject);

            allSingle_List.Clear();

            for (int i = 0; i < allMultiple_List.Count; i++)
                Destroy(allMultiple_List[i].gameObject);

            allMultiple_List.Clear();

            for (int i = 0; i < allTrueFalse_List.Count; i++)
                Destroy(allTrueFalse_List[i].gameObject);

            allTrueFalse_List.Clear();

            for (int i = 0; i < allBlank_List.Count; i++)
                Destroy(allBlank_List[i].gameObject);

            allBlank_List.Clear();

            for (int i = 0; i < allShortAnswer_List.Count; i++)
                Destroy(allShortAnswer_List[i].gameObject);

            allShortAnswer_List.Clear();

            // 创建所有题目
            for (int i = 0; i < quesDataModel.Single_Num.Value; i++)
            {
                HK_SingleChoiceItem item = Instantiate(singleItem_Prefab, singleChoiceContent);
                item.InitQuesItem(quesDataModel.QuizData.Value.SingleChoice_List[i], i + 1);
                allSingle_List.Add(item);
            }

            for (int i = 0; i < quesDataModel.Multiple_Num.Value; i++)
            {
                HK_MultipleChoiceItem item = Instantiate(multipleItem_Prefab, multipleChoiceContent);
                item.InitQuesItem(quesDataModel.QuizData.Value.MultipleChoice_List[i], i + 1);
                allMultiple_List.Add(item);
            }

            for (int i = 0; i < quesDataModel.TrueFalse_Num.Value; i++)
            {
                HK_TrueFalseItem item = Instantiate(trueFalseItem_Prefab, trueFalseContent);
                item.InitQuesItem(quesDataModel.QuizData.Value.TrueFalse_List[i], i + 1);
                allTrueFalse_List.Add(item);
            }

            for (int i = 0; i < quesDataModel.Blank_Num.Value; i++)
            {
                HK_BlankItem item = Instantiate(blankItem_Prefab, blankContent);
                item.InitQuesItem(quesDataModel.QuizData.Value.Blank_List[i], i + 1);
                allBlank_List.Add(item);
            }

            for (int i = 0; i < quesDataModel.ShortAnswer_Num.Value; i++)
            {
                HK_ShortAnswerItem item = Instantiate(shortAnswerItem_Prefab, shortAnswerContent);
                item.InitQuesItem(quesDataModel.QuizData.Value.ShortAnswer_List[i], i + 1);
                allShortAnswer_List.Add(item);
            }

            OnSingleToggleChanged(true);
        }

        void OnSingleToggleChanged(bool isOn)
        {
            if (!isOn)
                return;

            foreach (var item in quesPanel_List)
            {
                item.SetActive(false);
            }

            singleChoicePanel.SetActive(true);
            singleChoicePanel.GetComponent<ScrollRect>().verticalScrollbar.value = 1;
        }

        void onMultipleToggleChanged(bool isOn)
        {
            if (!isOn)
                return;

            foreach (var item in quesPanel_List)
            {
                item.SetActive(false);
            }

            multipleChoicePanel.SetActive(true);
            multipleChoicePanel.GetComponent<ScrollRect>().verticalScrollbar.value = 1;
        }

        void OnTrueFalseToggleChanged(bool isOn)
        {
            if (!isOn)
                return;

            foreach (var item in quesPanel_List)
            {
                item.SetActive(false);
            }

            trueFalsePanel.SetActive(true);
            trueFalsePanel.GetComponent<ScrollRect>().verticalScrollbar.value = 1;
        }

        void OnBlankToggleChanged(bool isOn)
        {
            if (!isOn)
                return;

            foreach (var item in quesPanel_List)
            {
                item.SetActive(false);
            }

            blankPanel.SetActive(true);
            blankPanel.GetComponent<ScrollRect>().verticalScrollbar.value = 1;
        }

        void OnShortAnswerToggleChanged(bool isOn)
        {
            if (!isOn)
                return;

            foreach (var item in quesPanel_List)
            {
                item.SetActive(false);
            }

            shortAnswerPanel.SetActive(true);
            shortAnswerPanel.GetComponent<ScrollRect>().verticalScrollbar.value = 1;
        }

        // 判断当前做题的进度
        void JudgeSubjectDoneProgress()
        {
            if (singleChoicePanel.activeInHierarchy)
            {
                singleDone_Num = 0;
                for (int i = 0; i < allSingle_List.Count; i++)
                {
                    if (allSingle_List[i].IsDone())
                        singleDone_Num++;
                }
                single_Toggle.GetComponentInChildren<Text>().text = string.Format("单选题({0}/{1})", singleDone_Num.ToString(), quesDataModel.Single_Num.Value.ToString());
            }

            if (multipleChoicePanel.activeInHierarchy)
            {
                multipleDone_Num = 0;
                for (int i = 0; i < allMultiple_List.Count; i++)
                {
                    if (allMultiple_List[i].IsDone())
                        multipleDone_Num++;
                }
                multiple_Toggle.GetComponentInChildren<Text>().text = string.Format("多选题({0}/{1})", multipleDone_Num.ToString(), quesDataModel.Multiple_Num.Value.ToString());
            }

            if (trueFalsePanel.activeInHierarchy)
            {
                trueFalseDone_Num = 0;
                for (int i = 0; i < allTrueFalse_List.Count; i++)
                {
                    if (allTrueFalse_List[i].IsDone())
                        trueFalseDone_Num++;
                }
                trueFalse_Toggle.GetComponentInChildren<Text>().text = string.Format("判断题({0}/{1})", trueFalseDone_Num.ToString(), quesDataModel.TrueFalse_Num.Value.ToString());
            }

            if (blankPanel.activeInHierarchy)
            {
                blankDone_Num = 0;
                for (int i = 0; i < allBlank_List.Count; i++)
                {
                    if (allBlank_List[i].IsDone())
                        blankDone_Num++;
                }
                blank_Toggle.GetComponentInChildren<Text>().text = string.Format("填空题({0}/{1})", blankDone_Num.ToString(), quesDataModel.Blank_Num.Value.ToString());
            }

            if (shortAnswerPanel.activeInHierarchy)
            {
                shortAnswer_Num = 0;
                for (int i = 0; i < allShortAnswer_List.Count; i++)
                {
                    if (allShortAnswer_List[i].IsDone())
                        shortAnswer_Num++;
                }
                shortAnswer_Toggle.GetComponentInChildren<Text>().text = string.Format("简答题({0}/{1})", shortAnswer_Num.ToString(), quesDataModel.ShortAnswer_Num.Value.ToString());
            }

            // 检查是否所有题目都已完成
            bool newResult = (singleDone_Num == quesDataModel.Single_Num.Value &&
                             multipleDone_Num == quesDataModel.Multiple_Num.Value &&
                             trueFalseDone_Num == quesDataModel.TrueFalse_Num.Value &&
                             blankDone_Num == quesDataModel.Blank_Num.Value &&
                             shortAnswer_Num == quesDataModel.ShortAnswer_Num.Value);

            isAllQuesComplete = newResult;
        }

        // 点击提交按钮
        void OnClickSubmitBtn()
        {
            if (!isAllQuesComplete)
            {
                quizTipsPanel.ShowTipsPanel("还有题目没有做完！", "继续", "放弃", TipType.Continue);
                return;
            }
            else
            {
                int single_rightNum = 0;

                for (int i = 0; i < allSingle_List.Count; i++)
                {
                    if (allSingle_List[i].IsCorrect())
                        single_rightNum++;
                }

                int multiple_rightNum = 0;

                for (int i = 0; i < allMultiple_List.Count; i++)
                {
                    if (allMultiple_List[i].IsCorrect())
                        multiple_rightNum++;
                }

                int trueFalse_rightNum = 0;

                for (int i = 0; i < allTrueFalse_List.Count; i++)
                {
                    if (!allTrueFalse_List[i].IsCorrect())
                        trueFalse_rightNum++;
                }

                int blank_rightNum = 0;

                for (int i = 0; i < allBlank_List.Count; i++)
                {
                    if (!allBlank_List[i].IsCorrect())
                        blank_rightNum++;
                }

                int shortAnswer_rightNum = 0;

                for (int i = 0; i < allShortAnswer_List.Count; i++)
                {
                    if (!allShortAnswer_List[i].IsCorrect())
                        shortAnswer_rightNum++;
                }

                // 最终得分
                int totalScore = quesDataModel.QuizData.Value.SingleChoice_Score * single_rightNum
                      + quesDataModel.QuizData.Value.MultipleChoice_Score * multiple_rightNum
                      + quesDataModel.QuizData.Value.TrueFalse_Score * trueFalse_rightNum
                      + quesDataModel.QuizData.Value.Blank_Score * blank_rightNum
                      + quesDataModel.QuizData.Value.ShortAnswer_Score * shortAnswer_rightNum;

                if (totalScore == quesDataModel.TotalScore.Value)
                {
                    quizTipsPanel.ShowTipsPanel("本次考试得分为：" + totalScore + "\n您获得了满分!", "", "结束", TipType.FullScore);
                }
                else
                {
                    quizTipsPanel.ShowTipsPanel("本次考试得分为：" + totalScore + "\n是否查看错题?", "是", "否", TipType.NotFullScore);
                }
            }
        }

        // 展示错题
        void OnShowWrongQuesItem()
        {
            tipsPanel_Go.SetActive(false);
            submit_Btn.gameObject.SetActive(false);

            // 设置显示错题时的网格大小
            panelToGridMap[singleChoicePanel].cellSize = wrongSingleSize;
            panelToGridMap[multipleChoicePanel].cellSize = wrongMultipleSize;
            panelToGridMap[trueFalsePanel].cellSize = wrongTrueFalseSize;
            panelToGridMap[blankPanel].cellSize = wrongBlankSize;
            panelToGridMap[shortAnswerPanel].cellSize = wrongShortAnswerSize;

            for (int i = 0; i < allSingle_List.Count; i++)
            {
                if (allSingle_List[i].IsCorrect())
                {
                    allSingle_List[i].gameObject.SetActive(false);
                }
                else
                {
                    allSingle_List[i].analysis_Txt.gameObject.SetActive(true);
                    allSingle_List[i].HideToggle();
                }
            }

            for (int i = 0; i < allMultiple_List.Count; i++)
            {
                if (allMultiple_List[i].IsCorrect())
                {
                    allMultiple_List[i].gameObject.SetActive(false);
                }
                else
                {
                    allMultiple_List[i].analysis_Txt.gameObject.SetActive(true);
                    allMultiple_List[i].HideToggle();
                }
            }

            for (int i = 0; i < allTrueFalse_List.Count; i++)
            {
                if (allTrueFalse_List[i].IsCorrect())
                {
                    allTrueFalse_List[i].gameObject.SetActive(false);
                }
                else
                {
                    allTrueFalse_List[i].analysis_Txt.gameObject.SetActive(true);
                    allTrueFalse_List[i].HideToggle();
                }
            }

            for (int i = 0; i < allBlank_List.Count; i++)
            {
                if (allBlank_List[i].IsCorrect())
                {
                    allBlank_List[i].gameObject.SetActive(false);
                }
                else
                {
                    allBlank_List[i].analysis_Txt.gameObject.SetActive(true);
                    allBlank_List[i].DisableInput();
                }
            }

            for (int i = 0; i < allShortAnswer_List.Count; i++)
            {
                if (allShortAnswer_List[i].IsCorrect())
                {
                    allShortAnswer_List[i].gameObject.SetActive(false);
                }
                else
                {
                    allShortAnswer_List[i].analysis_Txt.gameObject.SetActive(true);
                    allShortAnswer_List[i].DisableInput();
                }
            }
        }
    }
}